<template>
  <div class="system-backup">
    <el-row :gutter="20">
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>数据备份</span>
              <el-button type="primary" @click="createBackup">创建备份</el-button>
            </div>
          </template>
          
          <el-table :data="backupList" v-loading="loading" stripe>
            <el-table-column prop="name" label="备份名称" width="200" />
            <el-table-column prop="size" label="文件大小" width="120">
              <template #default="{ row }">
                {{ formatFileSize(row.size) }}
              </template>
            </el-table-column>
            <el-table-column prop="created_at" label="创建时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.created_at) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="{ row }">
                <el-button size="small" @click="downloadBackup(row)">下载</el-button>
                <el-button size="small" type="primary" @click="restoreBackup(row)">恢复</el-button>
                <el-button size="small" type="danger" @click="deleteBackup(row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="pagination.currentPage"
              v-model:page-size="pagination.pageSize"
              :total="pagination.total"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card>
          <template #header>
            <span>备份设置</span>
          </template>
          
          <el-form :model="backupSettings" label-width="100px">
            <el-form-item label="自动备份">
              <el-switch v-model="backupSettings.autoBackup" />
            </el-form-item>
            <el-form-item label="备份周期" v-if="backupSettings.autoBackup">
              <el-select v-model="backupSettings.backupCycle">
                <el-option label="每天" value="daily" />
                <el-option label="每周" value="weekly" />
                <el-option label="每月" value="monthly" />
              </el-select>
            </el-form-item>
            <el-form-item label="备份时间" v-if="backupSettings.autoBackup">
              <el-time-picker 
                v-model="backupSettings.backupTime" 
                format="HH:mm"
                value-format="HH:mm"
              />
            </el-form-item>
            <el-form-item label="保留份数">
              <el-input-number 
                v-model="backupSettings.keepCount" 
                :min="1" 
                :max="100"
              />
            </el-form-item>
            <el-form-item label="备份内容">
              <el-checkbox-group v-model="backupSettings.backupContent">
                <el-checkbox label="database">数据库</el-checkbox>
                <el-checkbox label="files">文件</el-checkbox>
                <el-checkbox label="logs">日志</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveBackupSettings">保存设置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        
        <el-card style="margin-top: 20px;">
          <template #header>
            <span>存储信息</span>
          </template>
          
          <div class="storage-info">
            <el-progress 
              :percentage="storageUsage" 
              :status="storageUsage > 80 ? 'exception' : ''"
            />
            <p>已使用: {{ formatFileSize(storageUsed) }} / {{ formatFileSize(storageTotal) }}</p>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 创建备份对话框 -->
    <el-dialog title="创建备份" v-model="backupDialogVisible" width="500px">
      <el-form :model="backupForm" label-width="100px">
        <el-form-item label="备份名称">
          <el-input v-model="backupForm.name" />
        </el-form-item>
        <el-form-item label="备份内容">
          <el-checkbox-group v-model="backupForm.content">
            <el-checkbox label="database">数据库</el-checkbox>
            <el-checkbox label="files">文件</el-checkbox>
            <el-checkbox label="logs">日志</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="压缩">
          <el-switch v-model="backupForm.compress" />
        </el-form-item>
        <el-form-item label="加密">
          <el-switch v-model="backupForm.encrypt" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="backupDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCreateBackup">创建</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatDate } from '@/utils/format'

interface Backup {
  id: number
  name: string
  size: number
  created_at: string
  status: 'completed' | 'processing' | 'failed'
}

const loading = ref(false)
const backupList = ref<Backup[]>([])
const backupDialogVisible = ref(false)
const storageUsage = ref(65)
const storageUsed = ref(650 * 1024 * 1024)
const storageTotal = ref(1024 * 1024 * 1024)

const backupForm = reactive({
  name: '',
  content: ['database', 'files'],
  compress: true,
  encrypt: false
})

const backupSettings = reactive({
  autoBackup: true,
  backupCycle: 'daily',
  backupTime: '02:00',
  keepCount: 7,
  backupContent: ['database', 'files']
})

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const loadBackupList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    backupList.value = [
      {
        id: 1,
        name: 'backup_20231201_0200',
        size: 120 * 1024 * 1024,
        created_at: '2023-12-01T02:00:00Z',
        status: 'completed'
      },
      {
        id: 2,
        name: 'backup_20231130_0200',
        size: 118 * 1024 * 1024,
        created_at: '2023-11-30T02:00:00Z',
        status: 'completed'
      }
    ]
    pagination.total = 2
  } catch (error) {
    ElMessage.error('获取备份列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

const createBackup = () => {
  backupForm.name = `backup_${new Date().toISOString().slice(0, 10).replace(/-/g, '')}_${('0' + new Date().getHours()).slice(-2)}${('0' + new Date().getMinutes()).slice(-2)}`
  backupDialogVisible.value = true
}

const confirmCreateBackup = () => {
  ElMessage.success('备份任务已创建')
  backupDialogVisible.value = false
  loadBackupList()
}

const downloadBackup = (backup: Backup) => {
  ElMessage.success(`开始下载备份: ${backup.name}`)
  // 这里应该调用API下载备份文件
}

const restoreBackup = async (backup: Backup) => {
  try {
    await ElMessageBox.confirm(
      `确定要恢复备份 "${backup.name}" 吗？这将覆盖当前数据。`,
      '警告',
      {
        type: 'warning'
      }
    )
    
    ElMessage.success(`开始恢复备份: ${backup.name}`)
    // 这里应该调用API恢复备份
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('恢复备份失败')
      console.error(error)
    }
  }
}

const deleteBackup = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除该备份吗？', '提示', {
      type: 'warning'
    })
    
    ElMessage.success('备份删除成功')
    loadBackupList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除备份失败')
      console.error(error)
    }
  }
}

const saveBackupSettings = () => {
  ElMessage.success('备份设置保存成功')
  // 这里应该调用API保存设置
}

const getStatusType = (status: string) => {
  switch (status) {
    case 'completed': return 'success'
    case 'processing': return 'primary'
    case 'failed': return 'danger'
    default: return 'info'
  }
}

const getStatusText = (status: string) => {
  switch (status) {
    case 'completed': return '已完成'
    case 'processing': return '处理中'
    case 'failed': return '失败'
    default: return status
  }
}

const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  loadBackupList()
}

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  loadBackupList()
}

onMounted(() => {
  loadBackupList()
})
</script>

<style scoped lang="scss">
.system-backup {
  padding: 20px;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .storage-info {
    p {
      margin: 10px 0 0 0;
      text-align: center;
    }
  }
}
</style>